package IBBB.view;

import IBBB.model.WordProperty;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.TextField;
import javafx.scene.web.WebEngine;
import javafx.scene.web.WebView;
import IBBB.network.sendmessage.send_query_word;
import javafx.stage.Stage;
import javafx.stage.StageStyle;

public class QueryWord {
    @FXML
    private TextField toQuery;
    @FXML
    private Button queryButton;
    @FXML
    private WebView presentWord;
    private WebEngine engine;

    private void warn(String s, String t) {
        FXMLLoader loader = new FXMLLoader();
        loader.setLocation(getClass().getResource("WarningPane.fxml"));
        try {
            Parent parent = loader.load();
            WarningPane wp = (WarningPane)loader.getController();
            wp.setMessage(s);
            Stage w = new Stage(StageStyle.UTILITY);
            w.setTitle(t);
            w.setScene(new Scene(parent, 350,220));
            w.show();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @FXML
    private void initialize() {
        engine = presentWord.getEngine();
        queryButton.setDisable(true);
        toQuery.textProperty().addListener(((observableValue, s, t1) -> {
            if (t1.equals("")) {
                queryButton.setDisable(true);
            } else {
                queryButton.setDisable(false);
            }
        }));
    }

    @FXML
    private void setQueryButtonAction() {
        queryButton.setDisable(true);
        send_query_word query_word = new send_query_word("localhost", toQuery.getText());
        Thread t = new Thread(query_word);
        query_word.messageProperty().addListener(((observableValue, s, t1) -> {
            switch (t1) {
                case "timeout": {
                    warn("网络异常", "警告");
                    queryButton.setDisable(false);
                    break;
                }
                case "spellWrong": {
                    engine.loadContent("<html><div><br><br><h1 style=\"text-align:center\">拼写出错啦或词库未收录</h1></div></html>");
                    queryButton.setDisable(false);
                    break;
                }
                case "wrong": {
                    warn("出现异常，查询失败", "警告");
                    queryButton.setDisable(false);
                    break;
                }
                case "success": {
                    WordProperty w = query_word.getWordProperty();
                    engine.loadContent(w.getPresentHtml());
                    queryButton.setDisable(false);
                    break;
                }
            }
        }));
        t.start();
    }
}
